package com.scaffold.springmvc.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.scaffold.commons.web.WebUtil;

public class RequestInterceptor implements HandlerInterceptor {
	private static final Logger log = LoggerFactory.getLogger(RequestInterceptor.class);
	
	private static final ThreadLocal<Long> handleTimeContext = new ThreadLocal<Long>();
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		handleTimeContext.set(System.currentTimeMillis());
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception 
	{
		String servletPath = request.getServletPath();
		Map params = WebUtil.getParameterMap(request);
		Long t = handleTimeContext.get();
		log.info("handleTime="+(System.currentTimeMillis()-t)+","+servletPath+", params="+params);
	}

}
